<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="../js/vue.js"></script>
</head>
<body>
  <div id="app">
    <h2>人员列表</h2>
    <input type="text" v-model="keyword">
    <button @click="sortType=2">升序</button>
    <button @click="sortType=3">降序</button>
    <button @click="sortType=1">原序</button>
    <ul>
      <li v-for="p in filterPersons" :key="p.id">
        {{p.name}}--{{p.age}}--{{p.gender}}
      </li>
    </ul>
  </div>

  <script>
    new Vue({
      el: '#app',
      data: {
        keyword: '',
        sortType: 1, // 排序类型  1: 不排序 2: 升序  3: 降序
        persons: [
          { id: '001', name: '马冬梅', age: 21, gender: '女' },
          { id: '002', name: '周冬雨', age: 19, gender: '女' },
          { id: '003', name: '周杰伦', age: 20, gender: '男' },
          { id: '004', name: '帅邓伦', age: 22, gender: '男' },
        ],
        filterPersons: []
      },

      methods: {
        updateFilterPersons () {
          // 计算出要显示的列表
          const {keyword, persons, sortType} = this
          // 过滤
          const arr = persons.filter(p => p.name.includes(keyword))
            // 排序
          if (sortType!==1) {
            arr.sort((p1, p2) => {
              if (sortType===2) {
                return p1.age - p2.age // 升序
              }
              return p2.age - p1.age // 降序
            })
          }

          // 更新filterPersons
          this.filterPersons = arr
        }
      },

      watch: {
        sortType: {
          handler () {
            this.updateFilterPersons()
          }
        },
        keyword: {
          handler () {
            this.updateFilterPersons()
          },
          immediate: true, // 初始化执行第一次
        }
      }
    })
  </script>
</body>
</html>